package com.spl.msplayer;

import java.io.IOException;

import com.spl.msplayer.settings.SettingActivity;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.provider.MediaStore.Audio.PlaylistsColumns;
import android.util.Log;
import android.widget.MediaController.MediaPlayerControl;

public class PlayerService extends Service implements MediaPlayerControl{

	private static PlayerService instance;
	private static VideoPlayer playerView;
	
	private MediaPlayer player;
	/**
	 * @return the player
	 */
	public MediaPlayer getPlayer() {
		return player;
	}

	// 0 init, 1 pause, 2 playing
	private int playingStatus;
	
	/**
	 * @return the playingStatus
	 */
	public int getPlayingStatus() {
		return playingStatus;
	}

	private boolean isVideoBGPlay;
	/**
	 * @return the isVideoBGPlay
	 */
	public boolean isVideoBGPlay() {
		return isVideoBGPlay;
	}

	/**
	 * @param isVideoBGPlay the isVideoBGPlay to set
	 */
	public void setVideoBGPlay(boolean isVideoBGPlay) {
		this.isVideoBGPlay = isVideoBGPlay;
	}

	boolean isOnlineStreaming = false;
	
	/**
	 * @return the isOnlineStreaming
	 */
	public boolean isOnlineStreaming() {
		return isOnlineStreaming;
	}

	/**
	 * @param isOnlineStreaming the isOnlineStreaming to set
	 */
	public void setOnlineStreaming(boolean isOnlineStreaming) {
		this.isOnlineStreaming = isOnlineStreaming;
	}

	private boolean isAudioBGPlay;
	/**
	 * @return the isAudioBGPlay
	 */
	public boolean isAudioBGPlay() {
		return isAudioBGPlay;
	}

	/**
	 * @param isAudioBGPlay the isAudioBGPlay to set
	 */
	public void setAudioBGPlay(boolean isAudioBGPlay) {
		this.isAudioBGPlay = isAudioBGPlay;
	}


	private String videopath;
	private int videoOrientation;
	
	/**
	 * @return the videoOrientation
	 */
	public int getVideoOrientation() {
		return videoOrientation;
	}

	/**
	 * @param videoOrientation the videoOrientation to set
	 */
	public void setVideoOrientation(int videoOrientation) {
		this.videoOrientation = videoOrientation;
	}

	int currentPosition;
	boolean isPrepared = false;
	/**
	 * @return the isPrepared
	 */
	public boolean isPrepared() {
		return isPrepared;
	}

	public static PlayerService getInstance() {
		return instance;
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see android.app.Service#onCreate()
	 */
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		
		player = new MediaPlayer();
		player.setOnPreparedListener(new OnPreparedListener() {
			
			@Override
			public void onPrepared(MediaPlayer mp) {
				// TODO Auto-generated method stub
				isPrepared = true;
				Log.i("SUMPRO", "onPrepared");
				
				Log.i("SUMPRO", "onPrepared width:" + player.getVideoHeight());
				Log.i("SUMPRO", "onPrepared width:" + player.getVideoWidth());
				if(player.getVideoWidth() > player.getVideoHeight()) {
					videoOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
				} else {
					videoOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
				}
				if(playerView != null)
					playerView.onPreparedDone();
			}
		});
		player.setOnCompletionListener(new OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer mp) {
				// TODO Auto-generated method stub
				playingStatus = 1;
				if(isOnlineStreaming) {
					WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
							.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
					if(wifiLock.isHeld())
						wifiLock.release();
				}
			}
		});
		player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
		
		
		
		currentPosition = 0;
		playingStatus = 0;
		
		instance = this;
		Log.i("SUMPRO", "onCreate");
		
		//get playback setting
		SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
		isVideoBGPlay = sharedPref.getBoolean(SettingActivity.VIDEO_PLAYBG_SETTING, true);
		isAudioBGPlay = sharedPref.getBoolean(SettingActivity.AUDIO_PLAYBG_SETTING, false);
	}

	/* (non-Javadoc)
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
		Log.i("SUMPRO", "onDestroy");
		// TODO Auto-generated method stub
		if(player.isPlaying()) {
			player.stop();
		}
		player.release();
		player = null;
		if(isOnlineStreaming) {
			WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
					.createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
			if(wifiLock.isHeld())
				wifiLock.release();
		}
		super.onDestroy();
	}

	/* (non-Javadoc)
	 * @see android.app.Service#onStartCommand(android.content.Intent, int, int)
	 */
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i("SUMPRO", "onStartCommand");
		return super.onStartCommand(intent, flags, startId);
		
	}

	public void prepair(boolean isAsyn) {
		Log.i("SUMPRO", "prepair" + videopath);
		if(isAsyn) {
			isPrepared = false;
			if(videopath == null)
				return;
			else 
				player.prepareAsync();
		} else {
			try {
				player.prepare();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	
	public String getVideopath() {
		return videopath;
	}

	public void setVideopath(String videopath) {
		Log.i("SUMPRO", "setVideopath:" + videopath);
		this.videopath = videopath;
		try {
			player.reset();
			player.setAudioStreamType(AudioManager.STREAM_MUSIC);
			player.setDataSource(videopath);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		playerView = VideoPlayer.getInstance();
	}

	@Override
	public boolean canPause() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean canSeekBackward() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean canSeekForward() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public int getBufferPercentage() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int getCurrentPosition() {
		
		if(player == null)
			return 0;
		return player.getCurrentPosition();
	}

	@Override
	public int getDuration() {
		if(player == null)
			return 0;
		int dur = 0;
		try {
			dur = player.getDuration();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return dur;
	}

	@Override
	public boolean isPlaying() {
		
		if(player == null)
			return false;
		return player.isPlaying();
	}

	@Override
	public void seekTo(int pos) {
		if(player == null)
			return;
		player.seekTo(pos);
	}

	@Override
	public void start() {
		if(player == null)
			return;
		if(isOnlineStreaming){
			WifiLock wifiLock = ((WifiManager) getSystemService(Context.WIFI_SERVICE))
				    .createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");

				wifiLock.acquire();
		}
		player.start();
		playingStatus = 2;
		
	}

	@Override
	public void pause() {
		// TODO Auto-generated method stub
		if(player == null)
			return;
		player.pause();
		playingStatus = 1;
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	public void startForeground(){
		// assign the song name to songName
		Intent intent = new Intent(getApplicationContext(), VideoPlayer.class);
		intent.putExtra(MainScreen.RESUME_FROM_NOTIFICATION, true);
		PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
						intent,
		                PendingIntent.FLAG_UPDATE_CURRENT);
		NotificationManager nm = (NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
		Resources res = this.getResources();
		Notification.Builder builder = new Notification.Builder(getApplicationContext());
		builder.setContentIntent(pi)
								.setSmallIcon(R.drawable.ic_launcher)
								.setTicker("Playing")
								.setWhen(System.currentTimeMillis())
								.setAutoCancel(true)
								.setContentTitle("MS Player")
								.setContentText(videopath);
		Notification n = builder.build();
		startForeground(1, n);
		if(playerView != null)
			playerView.finish();
	}
	
	public void onPreviewPause() {
		Log.i("SUMPRO", "onPreviewPause " + isVideoBGPlay);
		if(!isVideoBGPlay) 
			pause();
		else
			startForeground();
	}
	
	public void onPreviewResume() {
		if(!isVideoBGPlay)
			start();
	}
	
	public void reset() {
		player.reset();
	}
	
	public void onPreviewAvailable() {
		
	}
}
